package services

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var oeBindSaleTxLogger *logrus.Logger

// InitOeBindSaleLogger 移除 init() 函数，改为显式初始化函数
func InitOeBindSaleLogger() {
	// 确保在 common 初始化后调用
	oeBindSaleTxLogger = core.InitLogger(common.LogsErrorMap[8])
}

type OeBindSaleService struct{}

// oeBindSaleRequest 定义广告主信息结构体
type oeBindSaleRequest struct {
	AccountID      string   `json:"account_id"`
	PersonCharge   string   `json:"person_charge"`
	Collaborator   []string `json:"collaborator"`
	FlagRemarkBool bool     `json:"flag_remark_bool"`
}

// oeBindSaleCurlResponse 定义统一返回结构
type oeBindSaleCurlResponse struct {
	Code int         `json:"code"`
	Data interface{} `json:"data,omitempty"`
	Msg  string      `json:"msg,omitempty"`
}

type Collaborator struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// AdvInfo 定义广告账户信息结构体
type AdvInfo struct {
	OptimizerID   string         `json:"optimizer_id"`
	OptimizerName string         `json:"optimizer_name"`
	Collaborator  []Collaborator `json:"collaborator"`
}

// AgentInfo 定义代理销售信息结构体
type AgentInfo struct {
	AgentID   string `json:"agent_id"`
	AgentName string `json:"agent_name"`
}

// OptimizerCollaboratorRequest 定义绑定请求的结构体
type OptimizerCollaboratorRequest struct {
	AssignType     string          `json:"assignType"`
	AssignSource   string          `json:"assignSource"`
	AssignTarget   string          `json:"assignTarget"`
	AssignPackages []AssignPackage `json:"assignPackages"`
}

// AssignPackage 定义分配包结构
type AssignPackage struct {
	AdvID           string   `json:"advId"`
	OptimizerID     string   `json:"optimizerId"`
	CollaboratorIDs []string `json:"collaboratorIds"`
}

// OptimizerCollaboratorResponse 定义绑定响应的结构
type OptimizerCollaboratorResponse struct {
	Code int `json:"code"`
	Data struct {
		AdvResultList []struct {
			Success bool   `json:"success"`
			AdvID   string `json:"advId"`
			Message string `json:"msg"`
		} `json:"advResultList"`
	} `json:"data"`
	Msg string `json:"msg"`
}

func (s *OeBindSaleService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	var msg = &models.Msg{}

	fmt.Println("oeBindSaleTxLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		oeBindSaleTxLogger.Error("巨量绑定销售获取数据失败", common.LogsErrorMap[2], msgId, err)
		return err
	}

	oeBindSaleTxLogger.Info("oeBindSaleTxLogger", "原始结构：", content)

	// 处理需要的数据结构
	accounts, err := s.oeBindSaleAnalyzeContent(content)
	if err != nil {
		oeBindSaleTxLogger.Error(err)
		return err
	}

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	fmt.Println("oeBindSaleTxLogger", accounts, "移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, err := rdb.Get(ctx, "laravel_database_oead_adv_cookies").Result()
	token, err := rdb.Get(ctx, "laravel_database_oead_adv_cg_csrf_token").Result()

	fmt.Println("oeBindSaleTxLogger", "Cookies:", cookies, "tk:", token)

	// 查询任务
	var job models.Job
	if err = common.DB.Where("id = ?", jobId).First(&job).Error; err != nil {
		oeBindSaleTxLogger.Error("查询完整任务记录", common.LogsErrorMap[2], jobId, err)
		return err
	}

	// 查找失败负责人邮箱
	var errorPersonCharge []string

	// 统计失败协作人邮箱
	var errorCollaborator []string

	// 统计绑定成功
	var successCollaborator []string

	// 统计绑定失败
	errorBindUser := make(map[string][]string)

	for _, account := range accounts {
		advInfo, err := s.QueryAdvList(account.AccountID, msg, cookies, token)
		oeBindSaleTxLogger.Infof("获取负责人: %s", advInfo) // 添加这行日志
		if err != nil || advInfo == nil {
			// 错误处理或记录失败
			errorBindUser["查找人员错误"] = append(errorBindUser["查找人员错误"], account.AccountID)
			oeBindSaleTxLogger.Errorf("查询广告账户信息失败: %v", err)
			break
		}

		// 获取负责人ID
		optimizerId := advInfo.OptimizerID

		oeBindSaleTxLogger.Infof("广告账户ID: %s, 获取到的负责人ID: '%s'", account.AccountID, optimizerId) // 添加这行日志
		if optimizerId == "" {
			errorPersonCharge = append(errorPersonCharge, account.PersonCharge)
			oeBindSaleTxLogger.Warnf("广告账户ID: %s 未找到负责人ID", account.AccountID)
		}

		// 使用结构体字段访问
		var collaboratorId []string
		for _, collab := range advInfo.Collaborator {
			if collab.ID != "" {
				collaboratorId = append(collaboratorId, collab.ID)
			}
		}

		// 获取负责人ID
		if account.PersonCharge != "" {
			agentInfo, err := s.GetAgentSale(account.PersonCharge, cookies)
			if err != nil || agentInfo == nil {
				errorPersonCharge = append(errorPersonCharge, account.PersonCharge)
				oeBindSaleTxLogger.Warnf("未找到负责人信息: %s", account.PersonCharge)
			} else {
				optimizerId = agentInfo.AgentID
			}
		}

		// 获取协作者ID列表
		for _, email := range account.Collaborator {
			agentInfo, err := s.GetAgentSale(email, cookies)
			if err != nil || agentInfo == nil {
				errorCollaborator = append(errorCollaborator, email)
				oeBindSaleTxLogger.Warnf("未找到协作者信息: %s", email)
			} else {
				collaboratorId = append(collaboratorId, agentInfo.AgentID)
			}
		}

		advResponse, err := s.OptimizerCollaborators(account.AccountID, optimizerId, collaboratorId, msg, cookies, token)

		// 处理绑定结果
		if advResponse != nil && advResponse.Code == 0 && len(advResponse.Data.AdvResultList) > 0 {
			// 记录绑定成功
			successCollaborator = append(successCollaborator, account.AccountID)
			oeBindSaleTxLogger.Infof("广告账户ID: %s 绑定成功", account.AccountID)
		} else {
			var errorMsg string
			if err != nil {
				errorMsg = err.Error()
			} else if advResponse != nil {
				errorMsg = advResponse.Msg
			} else {
				errorMsg = "未知错误"
			}

			// 记录绑定失败
			if errorMsg == "" {
				errorMsg = "未知错误"
			}

			errorBindUser[errorMsg] = append(errorBindUser[errorMsg], account.AccountID)
			oeBindSaleTxLogger.Errorf("广告账户ID: %s 绑定失败: %s", account.AccountID, errorMsg)
		}
		// 打印调试信息
		oeBindSaleTxLogger.Infof("广告账户ID: %s, 负责人ID: %s, 协作者ID: %v",
			account.AccountID, optimizerId, collaboratorId)

	}

	// 处理错误信息
	if len(errorPersonCharge) > 0 {
		errorMsg := "未找到以下负责人: " + strings.Join(errorPersonCharge, ", ")
		err := BendiSendText(msg.Content+"\n-----------------------------------\n"+errorMsg, msg.RoomID, msg.Sender)
		if err != nil {
			return err
		}
	}
	if len(errorCollaborator) > 0 {
		errorMsg := "未找到以下协作者: " + strings.Join(errorCollaborator, ", ")
		err := BendiSendText(msg.Content+"\n-----------------------------------\n"+errorMsg, msg.RoomID, msg.Sender)
		if err != nil {
			return err
		}
	}
	if len(successCollaborator) > 0 {
		successMsg := "成功绑定协作者: " + strings.Join(successCollaborator, ", ")
		err := BendiSendText(msg.Content+"\n-----------------------------------\n"+successMsg, msg.RoomID, msg.Sender)
		if err != nil {
			return err
		}
	}

	if len(errorBindUser) > 0 {
		var errorMessages []string
		for errorMsg, advIDs := range errorBindUser {
			// 过滤空值
			validIDs := make([]string, 0, len(advIDs))
			for _, id := range advIDs {
				if id != "" {
					validIDs = append(validIDs, id)
				}
			}

			if len(validIDs) > 0 {
				errorMessages = append(errorMessages,
					fmt.Sprintf("%s：%s", errorMsg, strings.Join(validIDs, ",")))
			}
		}

		// 拼接错误信息
		if len(errorMessages) > 0 {
			errorMessageString := strings.Join(errorMessages, "\n")

			// 发送错误消息
			if err := BendiSendText(
				msg.Content+"\n"+"-----------------------------------"+"\n"+errorMessageString,
				msg.RoomID,
				msg.Sender,
			); err != nil {
				oeBindSaleTxLogger.Errorf("发送失败原因消息失败: %v", err)
				return err
			}
		}
	}

	return nil
}

// oeBindSaleAnalyzeContent 解析内容为广告主信息数组
func (s *OeBindSaleService) oeBindSaleAnalyzeContent(content []string) ([]oeBindSaleRequest, error) {
	// 初始化结果变量
	var accountIDs []string
	var personCharge string
	var flagRemarkBool bool
	var collaborator []string

	// 编译正则表达式（支持中文逗号、顿号）
	sepRegex, err := regexp.Compile(`[,，、]`)
	if err != nil {
		oeBindSaleTxLogger.Error("广告主ID分隔符正则表达式编译失败", err)
		return nil, fmt.Errorf("正则表达式编译失败: %w", err)
	}

	// 遍历内容行
	for _, line := range content {
		// 广告账户ID
		if strings.HasPrefix(line, "广告账户ID:") {
			raw := strings.TrimPrefix(line, "广告账户ID:")
			ids := sepRegex.Split(raw, -1)
			for _, id := range ids {
				trimmed := strings.TrimSpace(id)
				if trimmed != "" {
					accountIDs = append(accountIDs, trimmed)
				}
			}
		}
		// 负责人
		if strings.HasPrefix(line, "负责人:") {
			personCharge = strings.TrimSpace(strings.TrimPrefix(line, "负责人:"))
		}
		// 备注获取
		if strings.HasPrefix(line, "备注:") {
			flagRemark := strings.TrimSpace(strings.TrimPrefix(line, "备注:"))
			if flagRemark != "" {
				if flagRemark != "移除旧数据" {
					return nil, fmt.Errorf("如需解绑所有旧销售，请输入：移除旧数据")
				}
				flagRemarkBool = true
			}
		}
		// 协作者
		if strings.HasPrefix(line, "协作者:") {
			raw := strings.TrimPrefix(line, "协作者:")
			emails := sepRegex.Split(raw, -1)
			for _, email := range emails {
				trimmed := strings.TrimSpace(email)
				if trimmed != "" {
					collaborator = append(collaborator, trimmed)
				}
			}
		}
	}
	// 验证必要字段
	if len(accountIDs) == 0 {
		oeBindSaleTxLogger.Error("解析参数失败: 缺少广告账户ID")
		return nil, fmt.Errorf("解析参数失败: 缺少广告账户ID")
	}

	// 构建结果
	var result []oeBindSaleRequest
	for _, accountID := range accountIDs {
		result = append(result, oeBindSaleRequest{
			AccountID:      accountID,
			PersonCharge:   personCharge,
			Collaborator:   collaborator,
			FlagRemarkBool: flagRemarkBool,
		})
	}
	// 空数据警告（可选）
	if len(result) == 0 {
		oeBindSaleTxLogger.Warn("未解析到有效广告主ID")
		return nil, fmt.Errorf("未解析到有效广告主ID")
	}

	return result, nil
}

// QueryAdvList 查询广告账户信息
func (s *OeBindSaleService) QueryAdvList(advID string, msg *models.Msg, oeAdCookies, oeAdToken string) (*AdvInfo, error) {
	// 构造请求URL
	url := fmt.Sprintf("https://agent.oceanengine.com/agent/assign-adv/query/adv-list-v3?advId=%s&assignSource=BIDDING&page=1&size=10", advID)

	// 发送GET请求
	response, err := s.SendCurlRequest(url, nil, oeAdCookies, "GET", oeAdToken)
	if err != nil {
		oeBindSaleTxLogger.Infof("query_adv_list请求失败: %v", err)
		return nil, fmt.Errorf("查询广告账户失败: %v", err)
	}

	// 记录完整响应
	oeBindSaleTxLogger.Infof("query_adv_list记录curl请求信息: %v", response)

	// 检查响应码
	if response.Code != 0 {
		oeBindSaleTxLogger.Infof("query_adv_list请求错误: %v", response)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 解析响应数据
	oeBindSaleTxLogger.Infof("response.Data 的实际类型: %T, 值: %+v", response.Data, response.Data)

	// 解析响应数据
	var responseData map[string]interface{}
	switch v := response.Data.(type) {
	case map[string]interface{}:
		responseData = v
	case map[interface{}]interface{}:
		// 转换 map[interface{}]interface{} 为 map[string]interface{}
		responseData = make(map[string]interface{})
		for k, val := range v {
			if kStr, ok := k.(string); ok {
				responseData[kStr] = val
			}
		}
	default:
		return nil, fmt.Errorf("响应数据格式错误: 期望 map 类型，实际类型是 %T，值: %+v", response.Data, response.Data)
	}

	// 获取data数组
	dataRaw, ok := responseData["data"]
	if !ok {
		oeBindSaleTxLogger.Infof("responseData中未找到data字段: %+v", responseData)
		return nil, fmt.Errorf("响应数据中未找到data字段")
	}

	// 获取data数组
	dataArray, ok := dataRaw.([]interface{})
	if !ok {
		oeBindSaleTxLogger.Infof("data字段不是数组类型: %T, 值: %+v", dataRaw, dataRaw)
		return nil, fmt.Errorf("data字段不是数组类型，实际类型是 %T", dataRaw)
	}

	if len(dataArray) == 0 {
		// 发送文本消息
		if err := BendiSendText(
			msg.Content+"\n-----------------------------------\n媒体后台未找到该广告账户ID:"+advID+"，请切换分配状态查询",
			msg.RoomID,
			msg.Sender,
		); err != nil {
			oeBindSaleTxLogger.Errorf("发送错误消息失败: %v", err)
		}

		oeBindSaleTxLogger.Infof("query_adv_list查询不到广告账户ID: %s", advID)
		return nil, fmt.Errorf("未找到广告账户数据")
	}

	// 获取第一个数据项
	item, ok := dataArray[0].(map[string]interface{})
	if !ok {
		oeBindSaleTxLogger.Infof("数据项不是map类型: %T, 值: %+v", dataArray[0], dataArray[0])
		return nil, fmt.Errorf("数据项格式错误，不是map类型，实际类型是 %T", dataArray[0])
	}

	// 提取字段
	var optimizerID, optimizerName string
	if optID, ok := item["optimizerId"]; ok {
		if optID == nil {
			oeBindSaleTxLogger.Info("optimizerId字段为nil")
		} else {
			// 处理不同数据类型
			switch v := optID.(type) {
			case string:
				optimizerID = v
			case float64:
				optimizerID = fmt.Sprintf("%.0f", v)
			case int:
				optimizerID = fmt.Sprintf("%d", v)
			default:
				oeBindSaleTxLogger.Warnf("optimizerId字段是未知类型: %T, 值: %v", optID, optID)
			}
		}
	} else {
		oeBindSaleTxLogger.Warn("未找到optimizerId字段")
	}

	if optName, ok := item["optimizerName"]; ok {
		if optName == nil {
			oeBindSaleTxLogger.Info("optimizerName字段为nil")
		} else {
			// 处理不同数据类型
			switch v := optName.(type) {
			case string:
				optimizerName = v
			case float64:
				optimizerName = fmt.Sprintf("%.0f", v)
			case int:
				optimizerName = fmt.Sprintf("%d", v)
			default:
				oeBindSaleTxLogger.Warnf("optimizerName字段是未知类型: %T, 值: %v", optName, optName)
			}
		}
	} else {
		oeBindSaleTxLogger.Warn("未找到optimizerName字段")
	}

	// 处理协作者
	var collaborators []Collaborator
	if collabArr, ok := item["collaborator"].([]interface{}); ok {
		for _, v := range collabArr {
			if collabMap, ok := v.(map[string]interface{}); ok {
				collaborators = append(collaborators, Collaborator{
					ID:   fmt.Sprintf("%v", collabMap["id"]),
					Name: fmt.Sprintf("%v", collabMap["name"]),
				})
			}
		}
	}

	// 返回结果
	return &AdvInfo{
		OptimizerID:   optimizerID,
		OptimizerName: optimizerName,
		Collaborator:  collaborators,
	}, nil
}

// SendCurlRequest 发送HTTP请求
func (s *OeBindSaleService) SendCurlRequest(url string, postData interface{}, xhsCookies string, method string, oeCsrfToken string) (*oeBindSaleCurlResponse, error) {
	// 创建请求上下文
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 序列化POST数据
	var bodyReader io.Reader
	if postData != nil {
		jsonData, err := json.Marshal(postData)
		if err != nil {
			return nil, fmt.Errorf("JSON序列化失败: %v", err)
		}
		bodyReader = bytes.NewBuffer(jsonData)
	}

	// 创建请求
	req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	req.Header.Set("Cookie", xhsCookies)
	if oeCsrfToken != "" {
		req.Header.Set("Cg-Csrf-Token", oeCsrfToken)
	}

	// 创建自定义客户端
	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	copyAccountTxLogger.Info("获取后得参数格式：", string(respBody))

	// 解析JSON响应
	var responseData map[string]interface{}
	if err := json.Unmarshal(respBody, &responseData); err != nil {
		return nil, fmt.Errorf("JSON解析失败: %v", err)
	}

	// 构建返回结果
	response := &oeBindSaleCurlResponse{}
	if code, ok := responseData["code"].(float64); ok {
		response.Code = int(code)
	} else {
		return nil, fmt.Errorf("响应中未找到code字段")
	}

	if data, ok := responseData["data"]; ok {
		response.Data = data
	}

	if msg, ok := responseData["msg"].(string); ok {
		response.Msg = msg
	}

	return response, nil
}

// GetAgentSale 获取代理销售信息
func (s *OeBindSaleService) GetAgentSale(email string, oeAdCookies string) (*AgentInfo, error) {
	// 构造请求URL
	url := "https://bsm.oceanengine.com/apps/bsm_web/back_end/agent/list/"

	// 构造POST数据
	postData := map[string]interface{}{
		"pageNo":      1,
		"page":        1,
		"pageSize":    10,
		"filters":     map[string]string{"nameOrEmail": email},
		"sorter":      []interface{}{},
		"nameOrEmail": email,
	}

	// 发送POST请求
	response, err := s.SendCurlRequest(url, postData, oeAdCookies, "POST", "")
	if err != nil {
		oeBindSaleTxLogger.Infof("get_agent_sale请求失败: %v", err)
		return nil, fmt.Errorf("查询代理销售失败: %v", err)
	}

	// 记录完整响应
	oeBindSaleTxLogger.Infof("get_agent_sale记录curl请求信息: %v", response)

	// 检查响应码
	if response.Code != 1 {
		oeBindSaleTxLogger.Infof("get_agent_sale请求错误: %v", response)
		return nil, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 解析响应数据
	var responseData map[string]interface{}
	switch v := response.Data.(type) {
	case map[string]interface{}:
		responseData = v
	case map[interface{}]interface{}:
		// 转换 map[interface{}]interface{} 为 map[string]interface{}
		responseData = make(map[string]interface{})
		for k, val := range v {
			if kStr, ok := k.(string); ok {
				responseData[kStr] = val
			}
		}
	default:
		return nil, fmt.Errorf("第三个接口响应数据格式错误: 期望 map 类型，实际类型是 %T，值: %+v", response.Data, response.Data)
	}

	oeBindSaleTxLogger.Infof("解析后响应的数据: %s", responseData)

	// 获取data数组
	dataArray, ok := responseData["data"].([]interface{})
	if !ok || len(dataArray) == 0 {
		oeBindSaleTxLogger.Infof("get_agent_sale查询不到代理销售信息: %s", email)
		return nil, fmt.Errorf("未找到代理销售数据")
	}

	// 获取第一个数据项
	item, ok := dataArray[0].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("数据项格式错误")
	}

	// 提取字段
	agentID, _ := item["id"].(float64)
	agentName, _ := item["name"].(string)

	oeBindSaleTxLogger.Infof("销售ID类型: %T", item["id"])
	oeBindSaleTxLogger.Infof("销售ID: %f，销售名称: %s", agentID, agentName)

	// 返回结果
	return &AgentInfo{
		AgentID:   strconv.Itoa(int(agentID)),
		AgentName: agentName,
	}, nil
}

// OptimizerCollaborators 发送绑定负责人和协作者的请求
func (s *OeBindSaleService) OptimizerCollaborators(advID, optimizerID string, collaboratorIDs []string, msg *models.Msg, oeAdCookies, oeCsrfToken string) (*OptimizerCollaboratorResponse, error) {
	// 构造请求URL
	url := "https://agent.oceanengine.com/agent/assign-adv/assign/optimizer-collaborators-v3"

	// 构造请求数据
	postData := &OptimizerCollaboratorRequest{
		AssignType:   "AVERAGE",
		AssignSource: "BIDDING",
		AssignTarget: "ALL",
		AssignPackages: []AssignPackage{{
			AdvID:           advID,
			OptimizerID:     optimizerID,
			CollaboratorIDs: collaboratorIDs,
		}},
	}

	oeBindSaleTxLogger.Infof("oeBindSaleTxLogger提交的参数: %s", postData)

	// 发送POST请求
	response, err := s.SendCurlRequest(url, postData, oeAdCookies, "POST", oeCsrfToken)
	if err != nil {
		oeBindSaleTxLogger.Infof("optimizer_collaborators请求失败: %v", err)
		return nil, fmt.Errorf("发送绑定请求失败: %v", err)
	}

	// 记录完整响应
	oeBindSaleTxLogger.Infof("optimizer_collaborators记录curl请求信息: %v", response)

	if response.Code != 0 {
		// 记录错误信息
		oeBindSaleTxLogger.Infof("optimizer_collaborators请求错误: %v", response)

		return &OptimizerCollaboratorResponse{
			Code: 1,
			Data: struct {
				AdvResultList []struct {
					Success bool   `json:"success"`
					AdvID   string `json:"advId"`
					Message string `json:"msg"`
				} `json:"advResultList"`
			}{},
			Msg: response.Msg,
		}, fmt.Errorf("接口返回错误: %s", response.Msg)
	}

	// 解析响应数据
	var responseData map[string]interface{}
	switch v := response.Data.(type) {
	case map[string]interface{}:
		responseData = v
	case map[interface{}]interface{}:
		// 转换 map[interface{}]interface{} 为 map[string]interface{}
		responseData = make(map[string]interface{})
		for k, val := range v {
			if kStr, ok := k.(string); ok {
				responseData[kStr] = val
			}
		}
	default:
		return nil, fmt.Errorf("第二个接口响应数据格式错误: 期望 map 类型，实际类型是 %T，值: %+v", response.Data, response.Data)
	}

	// 构建返回结果
	optResponse := &OptimizerCollaboratorResponse{
		Code: response.Code,
		Msg:  response.Msg,
	}

	// 解析advResultList
	if advResultList, ok := responseData["advResultList"].([]interface{}); ok && len(advResultList) > 0 {
		if firstItem, ok := advResultList[0].(map[string]interface{}); ok {
			if success, ok := firstItem["success"].(bool); ok {
				if !success {
					if errorMsg, ok := firstItem["msg"].(string); ok {
						optResponse.Code = 1
						optResponse.Msg = errorMsg

						// 发送错误消息
						if err := BendiSendText(
							msg.Content+"\n-----------------------------------\n绑定账号失败！2"+errorMsg,
							msg.RoomID,
							msg.Sender,
						); err != nil {
							oeBindSaleTxLogger.Errorf("发送错误消息失败: %v", err)
						}

						return optResponse, fmt.Errorf("绑定失败: %s", errorMsg)
					}
				}

				advID, _ := firstItem["advId"].(float64)
				ItoaAdvID := strconv.Itoa(int(advID))
				// 成功绑定
				optResponse.Data.AdvResultList = append(optResponse.Data.AdvResultList, struct {
					Success bool   `json:"success"`
					AdvID   string `json:"advId"`
					Message string `json:"msg"`
				}{Success: true, AdvID: ItoaAdvID})
			}
		}
	}

	return optResponse, nil
}
